#!/bin/sh
# Copyright (c) 2012, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.
# created on 2012-03-10

# A simple eject & wvdial hack for ZTE MF195 on Ubuntu 11.10.
# This should be called by the udev USB key on insertion.
# BUG: this script is called twice because maybe the rule
#  is not specific enough. As I didn't have time to
#  properly solve this, I simply added locking to
#  make rapidly starting two instances impossible.

{
 #BEGIN hack
 LOCK=/tmp/`basename $0`
 mkdir $LOCK
 S=$?
 if [ $S -ne 1 ]
 then
  LOCKDATE=`ls -ld --time-style +%s $LOCK|tr -s " "|cut -d " " -f 6`
  NOW=`date +%s`
  AGE=`expr $NOW - $LOCKDATE`
  if [ $AGE -lt 30 ] ; then
   exit 1
  fi
 fi
 #END of hack

 date
 DEVCD=/dev/sr1
 DEVMODEM=/dev/ttyACM0
 echo "info: waiting for $DEVCD "
 MAX=120 # timeout: 12 seconds
 I=0
 while
  # wait until the device settles
  ! [ -b $DEVCD ]
 do
  printf .
  sleep 0.1
  I=`expr $I + 1`
  if [ $I -gt $MAX ]; then
   echo "timeout!"
   rmdir $LOCK
   exit 1
  fi
 done
 echo
 printf "info: waiting for Ubuntu to show CD"
 sleep 2 # TODO: poll or try mounting it?
 echo
 if
  eject $DEVCD
 then
  echo "info: waiting for $DEVMODEM "
  I=0
  MAX=180 # 18 seconds timeout
  while
   # wait until usb_modeswitch switches to modem mode
   ! [ -c $DEVMODEM ]
  do
   sleep 0.1
   printf .
   I=`expr $I + 1`
   if [ $I -gt $MAX ]; then
    echo "timeout!"
    rmdir $LOCK
    exit 1
   fi
  done
  echo
  printf "info: waiting to register on GSM"
  sleep 20 # TODO: poll registration status via TTY
  echo

  wvdial

  # hack
  rmdir $LOCK
 else
  echo "error: can't eject $DEVCD"
  # hack
  rmdir $LOCK
 fi
} >> /var/log/tmobile_mf195.log 2>&1 &
